package com.example.agriapp.view.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.example.agriapp.R;
import com.example.agriapp.data.AgriDatabaseHelper;
import com.example.agriapp.model.bean.FeedItem;
import com.example.agriapp.util.PathUtil;

import android.content.Intent;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.Nullable;

import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

public class PostActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_PICK_MEDIA = 1001;

    private ImageButton btnBack;
    private LinearLayout btnAddMedia;
    private Button btnPublish;
    private EditText etContent;
    private ImageView ivSelectedImage;
    private String selectedImagePath;
    private AgriDatabaseHelper agriDatabaseHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.bottom_nav_icon_selected));
        // 初始化视图
        initViews();
        // 设置点击监听
        setupClickListeners();
    }

    private void initViews() {
        ivSelectedImage = findViewById(R.id.ivData);
        btnBack = findViewById(R.id.btn_back);
        btnAddMedia = findViewById(R.id.btn_add_media);
        btnPublish = findViewById(R.id.btn_publish);
        etContent = findViewById(R.id.tv_hint);
        agriDatabaseHelper = new AgriDatabaseHelper(this);
    }

    private void setupClickListeners() {
        // 返回按钮
        btnBack.setOnClickListener(v -> finish());

        // 添加媒体
        btnAddMedia.setOnClickListener(v -> pickMedia());

        // 发布按钮
        btnPublish.setOnClickListener(v -> publishPost());
    }

    private void showMoreOptions() {
        // 这里实现更多选项的弹出菜单
        Toast.makeText(this, "更多选项", Toast.LENGTH_SHORT).show();
    }

    private void pickMedia() {
        // 打开相册或相机选择媒体
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_CODE_PICK_MEDIA);
    }

    private void publishPost() {
        String content = etContent.getText().toString().trim();
    
        if (content.isEmpty()) {
            Toast.makeText(this, "请填写动态内容", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建新的FeedItem
        FeedItem newFeed = new FeedItem(
                UUID.randomUUID().toString(),
                "current_user_id",  // 实际项目中应从用户管理模块获取
                "当前用户名",
                "current_avatar",
                content,
                new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date()),
                0, 0, false, false, null,
                selectedImagePath != null ? selectedImagePath : null
        );
        
        // 通过ContentProvider插入数据
        insertFeed(newFeed);
        
        // 设置返回结果
        Intent resultIntent = new Intent();
        resultIntent.putExtra("content", content);
        if (selectedImagePath != null) {
            resultIntent.putExtra("imageUri", Uri.parse(selectedImagePath));
        }
        setResult(RESULT_OK, resultIntent);
    }

    public void insertFeed(FeedItem feed) {
        boolean b = agriDatabaseHelper.insertFeed(feed);
        if (b) {
            Toast.makeText(this, "发布成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "发布失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_MEDIA && resultCode == Activity.RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                ivSelectedImage.setImageBitmap(bitmap);
                ivSelectedImage.setVisibility(View.VISIBLE);
                selectedImagePath = PathUtil.getRealPathFromUri(this, imageUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

    }
}